<template>
  <a-card class="page-main page-main-admin" :bordered="false" v-title data-title="标准样目录管理">
    <div class="container">
      <div class="hte-head-content">
        <span class="bold-font">标准样目录管理</span>
      </div>
      <div class="content-admin">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
           <a-col :span="8" class="hte-col-nowrap">
                <a-form-item label="模糊查询" prop="keyword">
                  <a-input v-model="queryParam.keyword" placeholder="请输入关键词"></a-input>
                </a-form-item>
              </a-col>
              <a-button type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="default" style="margin-left: 16px" @click="searchReset">重置</a-button>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('标准样目录管理')">导出</a-button>
     
       <a-button  type="primary" icon="import" @click="importExcelDataBtn"
            >导入</a-button
          >
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
          <a-menu-item key="2" @click="handleScope(selectedRowKeys,true)"><a-icon type="control"/>批量设置共享范围</a-menu-item>

        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
      <span v-if="selectedRowKeys.length == 1">
        <a-button @click="handleScope(selectedRowKeys)" style="margin-left: 8px"><a-icon type="control" /> 共享范围</a-button>
      </span>
       <a-button v-has="'stdSample:groupDep'"  @click="gotoDetail('/stdSample/dataGroup/标准样/dep')">组织架构组管理</a-button>
      <a-button v-has="'stdSample:groupUser'" @click="gotoDetail('/stdSample/dataGroup/标准样/user')">用户组管理</a-button>
    </div>
 <div class="data-main" :class="{'shrinkage': shrinkageFlag}">          
        <div class="box-left ant-table-scroll" >
          <div class="tree-title">
            <span class="bold">目录</span>
            <a-icon type="menu-fold" @click="shrinkageFlag = !shrinkageFlag"  :title="!shrinkageFlag? '收缩目录' : '展开目录'"/>
          </div>
          <div class="tree" v-if="!shrinkageFlag"> 
            <a-input-search allow-clear style="margin-bottom: 8px" v-model="searchValue" placeholder="搜索目录" @search="onChangeTree" />
            <a-tree                             
              :tree-data="treeData"
              :selectedKeys="treeSelectedKeys"
              @select="onSelectClass"
              @expand="onExpand"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :replaceFields="{children:'children', title:'name', key:'id' }"
            >
             <template slot="title" slot-scope="{title}">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{title.substr(0, title.indexOf(searchValue))}}
                  <span style="color: #f50">{{searchValue}}</span>
                  {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
                </span>
                <span v-else>{{title}}</span>
              </template>
            </a-tree>
          </div>
        </div>
    <!-- table区域-begin -->

    <div class="box-right">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleScope([record.id])">共享范围</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
      </div>
    <std-sample-type-modal ref="modalForm" @ok="modalFormOk"></std-sample-type-modal>
    </div>
    </div>
    <LuckSheetPaste :title="'目录管理'" ref="luckSheetPaste" :columnsExcel="columnsExcel"  @handleOkExcel="handleOkExcel" ></LuckSheetPaste>
    <StdSampleScopeListModal ref="scope"></StdSampleScopeListModal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import StdSampleTypeModal from './modules/StdSampleTypeModal'
  import { isDateYYYYMMDD,isNumber,isNumberOrFload } from '@/utils/validate'
  
  import { postAction, getAction } from '@/api/manage'
  const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

  export default {
    name: 'StdSampleTypeList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      StdSampleTypeModal,
      LuckSheetPaste:()=> import('@/components/excelPaste/LuckSheetPaste'),
      StdSampleScopeListModal:()=> import('./modules/StdSampleScopeListModal'),
    },
    data () {
      return {
         isorter: {
        column: null,
        order: 'desc',
      },
      //自定义参数
      customParam:{},

        description: '标准样目录管理页面',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:'left',
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'编码',
            align:'left',
            dataIndex: 'code'
          },
          {
            title:'目录名称',
            align:'left',
            dataIndex: 'name'
          },
          {
            title:'目录全称',
            align:'left',
            dataIndex: 'nameAll'
          },
        
          {
            title:'状态',
            align:'left',
            dataIndex: 'status',
            customRender:function (text) {
              return text == 0?"启用":'禁用'
            }
          },
          
          {
            title:'备注',
            align:'left',
            dataIndex: 'remark'
          },
          {
            title:'排序',
            align:'left',
            dataIndex: 'orderNo'
          },
         
          
          {
            title: '操作',
            dataIndex: 'action',
            align:'left',
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
         columnsExcel:[
          {
            title:'父类目录全称',
            align:'left',
            dataIndex: 'nameAll'
          },
          {
            title:'编码',
            align:'left',
            dataIndex: 'code'
          },
          {
            title:'目录名称',
            align:'left',
            dataIndex: 'name'
          },
          
          {
            title:'状态',
            align:'left',
            dataIndex: 'status',
            
          },
          
          {
            title:'备注',
            align:'left',
            dataIndex: 'remark'
          },
          {
            title:'排序',
            align:'left',
            dataIndex: 'orderNo'
          },
         
        ],
        url: {
          list: "/stdSampleType/list",
          delete: "/stdSampleType/delete",
          deleteBatch: "/stdSampleType/deleteBatch",
          exportXlsUrl: "/stdSampleType/exportXls",
          importExcelUrl: "/stdSampleType/importExcel",
          addBatch: "/stdSampleType/addBatch",
          getTree:"/stdSampleType/getTree",
        },
        dictOptions:{},
        superFieldList:[],
         shrinkageFlag:false,
        treeData: [],
        dataList: [],
        treeSelectedKeys: [],
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        reloadTree:true,
      }
    },
    created() {
      this.getSuperFieldList();
      this.getTree(1)
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      handleScope(selectedRowKeys,batchFlag = false){
        var selectedRowKeys = selectedRowKeys
        let busKeys = selectedRowKeys.join(',')  
        let busKey = selectedRowKeys[0]
        this.$refs.scope.customParam ={busKey,batchFlag,busKeys} 
        this.$refs.scope.open({});
        
      },
      customLoadDataAfter(){
          //列表加载后
        this.getTree()

      },
      customDeleteAfter(){
         //删除后
         this.customParam.parentId = 0
         this.reloadTree = true
      },
      customSaveAfter(){
        //编辑保存后
        this.customParam.parentId = 0
        this.reloadTree = true
      },
      onSelectClass(selectedKeys,e) {
      if(e&&!e.selected){
        selectedKeys = this.treeSelectedKeys
      }
      this.customParam.parentId = selectedKeys[0]
      this.treeSelectedKeys = selectedKeys
      this.loadData(1)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChangeTree(value) {
      const that = this
      
      let expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, that.treeData);
          }
          return null;
        })
      expandedKeys =  expandedKeys.filter((item, i, self) => {
       return item && self.indexOf(item) === i
       });
      Object.assign(that, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    generateList(data){
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        data[i].scopedSlots={title:'title'}
        this.dataList.push({ key, title: node.title });
        if (node.children) {
          this.generateList(node.children);
        }
    }
    },
     getTree(arg){
      if(this.reloadTree ) {
          getAction(this.url.getTree,{}).then(res=>{
          if(res.code== 200){
             let treeData =  res.result || []
            let allTree = {children:null,title:'全部',name:'全部',id:0,key:0,value:0}
            treeData.unshift(allTree)
            this.generateList(treeData)
            this.treeData = treeData
            this.customParam.parentId = 0
            this.treeSelectedKeys = [0]
            this.reloadTree = false
          }else{
            this.$message.warning(res.message)
          }
        })
      }
        

      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'name',text:'目录名称'})
        fieldList.push({type:'int',value:'status',text:'状态状态'})
      
        this.superFieldList = fieldList
      },
      handleOkExcel(data,excelVm){
        for (let index = 0; index < data.length; index++) {
          const element = data[index];
          
          
          if(!element.name){
             excelVm.handleErroMsg('目录名称必填！')
            return 
          }
          if(!element.code){
             excelVm.handleErroMsg('编码必填！')
            return 
          }
          if(element.status == '禁用'){
            element.status = 1
          }else{
            element.status = 0
          }
          if(!!element.orderNo && !isNumberOrFload(element.orderNo,1,0)){
            excelVm.handleErroMsg('操作异常:排序请输入数字')
            return false; 
        }
         if(!!element.parentId && !isNumberOrFload(element.parentId,1,0)){
            excelVm.handleErroMsg('操作异常:父类目录编码请输入数字')
            return false; 
        }
        }

        postAction(this.url.addBatch,data).then(res => {
          
            if(res.code === 200){
              this.$message.success("导入成功");
              excelVm.afterClose()
              this.reloadTree = true
              this.getTree()
              this.loadData();
            }else{
              excelVm.handleErroMsg('操作异常:'+res.message);
            }
        }).catch(res=>{
            this.excelConfirmLoading = false;
            excelVm.handleErroMsg('操作异常:'+res.message);           
        })
      },
       importExcelDataBtn(){
        this.$refs.luckSheetPaste.showModalExcel();
      },
    gotoDetail(url, query={}){
      let routeUrl = this.$router.resolve({
        path: url,
        query: query
      });
      window.open(routeUrl.href, '_blank');
    },
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';
  @import '~@assets/less/hte-main.less';
  @import '~@views/library/hteFile.less';
.table-operator {
  margin-top: 10px;
}
</style>